package com.daifeng.gulimall.order.web;

import com.daifeng.gulimall.order.service.OrderTradeService;
import com.daifeng.gulimall.order.vo.OrderConfirmVo;
import com.daifeng.gulimall.order.vo.OrderSubmitVo;
import com.daifeng.gulimall.order.vo.SubmitOrderResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

@Controller
@Slf4j
public class webController {

    @Resource
    OrderTradeService orderTradeService;

    @GetMapping("/{page}.html")
    public String toPage(@PathVariable String page){
        return page;
    }

    /**
     * 结算
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        //获取当前登录用户的已选中购物车商品
        OrderConfirmVo item = orderTradeService.toTrade();
        model.addAttribute("data",item);
        return "index";
    }

    /**
     * 提交订单
     * @param orderSubmitVo
     * @return
     */
    @RequestMapping("/submitOrder")
    public String submitOrder( OrderSubmitVo orderSubmitVo , Model model, RedirectAttributes redirectAttributes){

        SubmitOrderResponseVo responseVo =orderTradeService.submitOrder(orderSubmitVo);
        log.error("======================订单创建成功{}:",responseVo);
        // 根据vo中定义的状态码来验证
        if (responseVo.getCode() == 0 ) { // 订单创建成功
            // 下单成功返回到支付页
            model.addAttribute("submitOrderResp",responseVo);
            return "pay";
        } else { // 下单失败
            // 根据状态码验证对应的状态
            String msg = "下单失败: ";
            switch (responseVo.getCode()) {
                case 1: msg += "订单信息过期，请刷新后再次提交"; break;
                case 2: msg += "订单商品价格发生变化，请确认后再次提交"; break;
                case 3: msg += "库存锁定失败，商品库存不足"; break;
            }
            redirectAttributes.addFlashAttribute("msg",msg);
            // 重新回到订单确认页面
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }



}
